package com.bw.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.lf5.util.DateFormatManager;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.bw.bean.Classes;
import com.bw.bean.Interview1;
import com.bw.bean.Month;
import com.bw.bean.StudentVo;
import com.bw.bean.Students;
import com.bw.bean.Teachers;
import com.bw.service.ClassesService;
import com.bw.service.JobService;
import com.bw.service.StudentsService;
import com.bw.service.TeachersService;
import com.bw.util.ExportExcel;
import com.bw.util.SessionUtil;

@Controller
public class TestController {
	private static Map<String, Object> map = new HashMap<String, Object>();
	@Autowired
	private JobService jobServiceImpl;
	@Autowired
	private TeachersService teachersServiceImpl;
	@Autowired
	private StudentsService studentsServiceImpl;
	@Autowired
	private ClassesService classesServiceImpl;
	/*@Autowired
	private InterviewService InterviewServiceImpl;*/

	@RequestMapping("test")
	public String test(HttpServletRequest req) {
		List<Month> list = new ArrayList<Month>();
		list.add(new Month("一月", 223));
		list.add(new Month("二月", 2223));
		list.add(new Month("三月", 3123));
		list.add(new Month("四月", 2413));
		list.add(new Month("五月", 2343));
		list.add(new Month("六月", 5533));
		list.add(new Month("七月", 7223));
		list.add(new Month("八月", 2423));
		list.add(new Month("九月", 2433));
		list.add(new Month("十月", 9253));
		list.add(new Month("十一月", 3223));
		list.add(new Month("十二月", 223));
		req.setAttribute("json", JSON.toJSONString(list));
		return "test";
	}
	@RequestMapping("getTable")
	public String getTable(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String fileName = "学生报表";
		/*response.reset();*/
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
		
		ExportExcel<StudentVo> ex = new ExportExcel<StudentVo>();
		String[] headers = {"编号", "项目经理", "学生姓名", "所在班级", "就业状态", "联系状态", "当日时间", "公司", "面试状态", "录音资料", "毕业前指导", "毕业后指导", "录音诊断", "今日是否联系", "面试时间"};
		//List<StudentVo> dataset = teachersServiceImpl.getStudents(1, "2017-03-22", "2017-03-23");
		List<StudentVo> dataset = SessionUtil.getDate(request);
		try {
			/*OutputStream out = new FileOutputStream(
					 "D:\\excel\\datas.xls");*/
			ex.exportExcel(headers, dataset, out);
			out.close();
			/*JOptionPane.showMessageDialog(null, "导出成功!");*/
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	@RequestMapping("getTables")
	public String getTables(){
		String[] title = {"编号", "学生姓名", "所在班级", "就业状态", "联系状态", "当日时间", "公司", "面试状态", "录音资料", "毕业前指导", "毕业后指导", "录音诊断", "今日是否联系", "面试时间"};
		List<StudentVo> stuList = teachersServiceImpl.getStudents(1, "2017-03-22", "2017-03-23");
		//创建excel工作薄
		@SuppressWarnings("resource")
		HSSFWorkbook workbook = new HSSFWorkbook();
		//创建一个工作表sheet
		Sheet createSheet = workbook.createSheet();
		//创建第一行
		Row row = createSheet.createRow(0);
		Cell cell = null;
		//插入第一行数据，id，name, sex
		for(int i = 0; i < title.length; i++){
			cell = row.createCell(i);
			cell.setCellValue(title[i]);
		}
		for(int i = 1; i <= stuList.size(); i++){
			Row nextrow = createSheet.createRow(i);
			Cell cell2 = nextrow.createCell(0);
			for(StudentVo vo : stuList){
					/*cell2.setCellValue(vo.getId());
					cell2 = nextrow.createCell(1);
					cell2.setCellValue(vo.getStudent().getName());
					cell2 = nextrow.createCell(2);
					cell2.setCellValue(vo.getCname());*/
			}
		}
		File file = new File("d://poi.xlsx");
		try {
			file.createNewFile();
			FileOutputStream stream = FileUtils.openOutputStream(file);
			workbook.write(stream);
			stream.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	/**
	 * 展示
	 * 
	 * @param teacherId
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping("list")
	public String list(Model model, HttpServletRequest request,
			 String tname, String sname, String time) throws Exception {
		List<StudentVo> stuList = new ArrayList();
		SimpleDateFormat sdf = null;
		sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date now = null;
		if(time == null||time == ""){
			time = new Date().toLocaleString();
			now = sdf.parse(time);
		}else{
			
			now = sdf.parse(time);
		}
		Calendar ca = Calendar.getInstance();
		ca.setTime(now);
		ca.add(Calendar.DATE, 1);
		Date tom = ca.getTime();
		ca.setTime(tom);
		ca.add(Calendar.DATE, -1);
		Date toDay = ca.getTime();
		String tomorrow = sdf.format(tom);
		String today = sdf.format(toDay);
		String cids = request.getParameter("cid");
		String t_cids = request.getParameter("t_cid");
		Teachers teacher = (Teachers) request.getSession().getAttribute("teacher");
		/*model.addAttribute("teacher", teacher);*/
		int t_cid = 0;
		if(t_cids == null || t_cids == "0"){
			
		}else{
			t_cid = Integer.parseInt(t_cids);
			List<Classes> list = teachersServiceImpl.getClasses(teacher.getId());
			model.addAttribute("classes", list);
			stuList = teachersServiceImpl.getStudents(t_cid, today, tomorrow);
			model.addAttribute("stuList", stuList);
			model.addAttribute("time", today);
			SessionUtil.addData(request, stuList);
			return "list";
		}
		boolean flag = false;
		int cid = 0;
		if(cids == null){
			
		}else{
			cid = Integer.parseInt(cids);
			flag = true;
		}if(tname == null){
			tname="";
		}else{
			flag = true;
		}
		if(sname == null){
			sname = "";
		}else{
			flag = true;
		}
		if(!flag){
			List<Classes> list = teachersServiceImpl.getClasses(teacher.getId());
			if(list.size()==1){
				int c = 0;
				for (Classes classes : list) {
					c = classes.getId();
				}
				stuList = teachersServiceImpl.getStudents(c, today, tomorrow);
				for (StudentVo s : stuList) {
					s.setTname(teacher.getName());
				}
				model.addAttribute("stuList", stuList);
				
			}else if(list.size()>1){
				model.addAttribute("classes", list);
			}
		}else{
			stuList = teachersServiceImpl.getOtherStudents(cid, tname, sname, today, tomorrow);
			List<Classes> list = teachersServiceImpl.getClasses(teacher.getId());
			model.addAttribute("classes", list);
			model.addAttribute("stuList", stuList);
			
		}
		model.addAttribute("time", today);
		model.addAttribute("sname", sname);
		model.addAttribute("tname", tname);
		SessionUtil.addData(request, stuList);
		return "list";
	}

	@RequestMapping("{zuoBiao}")
	public String zuoBiao(@PathVariable("zuoBiao") String zuoBiao) {
		return zuoBiao;
	}

	@RequestMapping("/")
	public String index() {
		return "index";
	}

	@RequestMapping("interview")
	public ModelAndView interview(int id) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		DateFormatManager dateFormatManager = new DateFormatManager("yyyy-MM-dd");
		String format = dateFormatManager.format(new Date());
		Students student = jobServiceImpl.selectStudentBySid(id);
		map.put("name", student.getName());
		map.put("classes", student.getClasses());
		map.put("date", format);
		map.put("sid", id);
		return new ModelAndView("interview", map);
	}

	@RequestMapping("addInterview")
	@ResponseBody
	public int addInterview(String msTime, Interview1 interview) throws ParseException {
		interview.setMstime(msTime);

		String time = interview.getTime();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date parse = format.parse(time);
		interview.setPresentDate(parse);
		try {
			jobServiceImpl.addInterview(interview);
		} catch (Exception e) {
			e.printStackTrace();
			return 2;
		}
		return 0;
	}
}
